package org.lightmtv.response;

import java.util.HashMap;
import java.util.Map;

import org.commontemplate.tools.web.ModelMap;
import org.lightcommons.json.JSONUtils;
import org.lightcommons.web.MimeType;
import org.lightmtv.LightMtvException;

public class JSONResponse extends TextResponse {

	private Map map;
	
	public JSONResponse(){
		setContentType(MimeType.JSON.getContentType());
		map = new HashMap<String, Object>();
	}
	
	public JSONResponse(Object obj) throws Exception {
		super();
		setContentType(MimeType.JSON.getContentType());
		if(obj instanceof Map)
			map = (Map) obj;
		else
			map = new ModelMap(obj);
	}
	
	@SuppressWarnings("unchecked")
	public JSONResponse put(String name,Object value){
		map.put(name, value);
		return this;
	}
	
	@Override
	public CharSequence getText() {
		try {
			return JSONUtils.toJson(map);
		} catch (Exception e) {
			throw new LightMtvException(e);
		}
	}
}